<template>

  <a-row :gutter="24" >
    <a-col :md="4" :sm="24">
      <a-card :bordered="false" :loading="treeLoading">
        <a-directory-tree
          :showIcon="false"
          :treeData="treeList"
          v-if="treeList.length"
          @select="handleClick"
          :defaultExpandAll="true"
          :replaceFields="replaceFields" />
      </a-card>
    </a-col>

    <a-col :md="19" :sm="24">
      <a-card :bordered="false">
        <div class="table-page-search-wrapper">
          <a-form layout="inline">
            <a-row :gutter="48">

              <a-col :md="8" :sm="24">
                <a-form-item label="网关名称">
                  <a-select style="width: 100%" v-model="queryParam.gatewayId" allow-clear placeholder="请选择网关名称" >
                    <a-select-option v-for="(item,ind) in gatewayList" :key="ind" :value="item.id" >{{ item.gatewayName }}</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>

              <a-col :md="!advanced && 8 || 24" :sm="24">
                <span class="table-page-search-submitButtons" style="padding-left: 16px;" :style="advanced && { float: 'right', overflow: 'hidden' } || {} ">
                  <a-button type="primary" v-if="hasPerm('bizGatewayTemperature:add')" class="btn_add" @click="$refs.addForm.add()" icon="plus">新增</a-button>
                  <a-button type="primary" class="btn_search_reset" @click="$refs.table.refresh(true), btnshow = true">查询</a-button>
                  <a-button style="margin-left: 8px" class="btn_search_reset" @click="() => {queryParam = {gatewayIds:gatewayIds.toString()};$refs.table.refresh()}">重置</a-button>
                  <a-button class="btn_search_reset" @click="btn" v-show="btnshow">切换</a-button>
                </span>
              </a-col>

            </a-row>
          </a-form>
        </div>

        <div v-if="isshow">
          <s-table
            ref="table"
            size="default"
            :columns="columns"
            :data="loadData"
            :alert="true"
            :rowKey="(record) => record.id">
            <span slot="action" slot-scope="text, record">
              <a v-if="hasPerm('bizGatewayTemperature:edit')" class="btn_edit" @click="$refs.editForm.edit(record)">编辑</a>
              <a-divider v-if="hasPerm('bizGatewayTemperature:edit')" type="vertical" />
              <a-popconfirm class="btn_del" placement="topRight" title="确认删除？" @confirm="() => del(record)">
                <a>删除</a>
              </a-popconfirm>
            </span>
          </s-table>
        </div>
        <div id="main" class="example" v-else style="width: 100%; height: 500px;">
          <a-spin />
        </div>

        <add-form ref="addForm" @ok="handleOk"/>
        <edit-form ref="editForm" @ok="handleOk"/>

      </a-card>
    </a-col>
  </a-row>
</template>

<script>
import * as echarts from 'echarts'
  import { STable } from '@/components'
import { page, del, getTemperatureByDate } from '@/api/modular/main/bizgatewaytemperature/bizGatewayTemperatureManage'
  import addForm from './addForm'
  import editForm from './editForm'
  import { treeList } from '@/api/modular/main/bizstation/bizStationManage'
  import { gatewayList } from '@/api/modular/main/bizgateway/bizGatewayManage'

  export default {
    components: {
      STable,
      addForm,
      editForm
    },

    data () {
      return {
        show: false,
        btnshow: false,
        isshow: true,
        advanced: false, // 高级搜索 展开/关闭
        queryParam: {}, // 查询参数
        columns: [ // 表头
/*          {
            title: '网关编号',
            dataIndex: 'gatewayCode'
          }, */
          {
            title: '网关名称',
            dataIndex: 'gatewayName'
          },
          {
            title: '温度',
            dataIndex: 'temperature'
          },
          {
            title: '时间',
            dataIndex: 'createTime',
            width: 200,
            align: 'center'
          }
        ],
        // 加载数据方法 必须为 Promise 对象
        loadData: parameter => {
          return page(Object.assign(parameter, this.queryParam)).then((res) => {
            return res.data
          })
        },
        selectedRowKeys: [],
        selectedRows: [],
        defaultExpandedKeys: [],
        treeList: [],
        replaceFields: {
          key: 'id'
        },
        treeLoading: true,
        gatewayList: [],
        stationId: ''
      }
    },
    created () {
      this.getStationTree()
    },
  methods: {
    btn () {
      this.isshow = !this.isshow
      this.getTemperatureByDate()
      setTimeout(() => {
        // 需要定时执行的代码
        this.$nextTick(() => {
          this.mainbt()
        })
      }, 1500)
    },
    // 折线图
    mainbt () {
      var chartDom = document.getElementById('main')
      var myChart = echarts.init(chartDom)
      var option

      let base = +new Date(1968, 9, 3)
      const oneDay = 24 * 3600 * 1000
      console.log(this.newData, 'data')
      console.log(this.newTime, 'time')
      const date = []
      const data = [111, 222, 3333, 442, 23, 23]
      for (let i = 1; i < 20000; i++) {
        var now = new Date((base += oneDay))
        date.push([now.getFullYear(), now.getMonth() + 1, now.getDate()].join('/'))
        data.push(Math.round((Math.random() - 0.5) * 20 + data[i - 1]))
      }
      option = {
        tooltip: {
          trigger: 'axis',
          position: function (pt) {
            return [pt[0], '10%']
          }
        },
        title: {
          left: 'center',
          text: ''
        },
        toolbox: {
          feature: {
            dataZoom: {
              yAxisIndex: 'none'
            },
            restore: {},
            saveAsImage: {}
          }
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: this.newTime
        },
        yAxis: {
          type: 'value',
          boundaryGap: [0, '100%']
        },
        dataZoom: [
          {
            type: 'inside',
            start: 0,
            end: 10
          },
          {
            start: 0,
            end: 10
          }
        ],
        series: [
          {
            name: '温度',
            type: 'line',
            symbol: 'none',
            sampling: 'lttb',
            itemStyle: {
              color: 'rgb(0, 255, 210)'
            },
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                {
                  offset: 0,
                  color: 'rgb(0, 255, 210)'
                },
                {
                  offset: 1,
                  color: 'rgb(32, 95, 255)'
                }
              ])
            },
            data: this.newData
          }
        ]
      }

      option && myChart.setOption(option)
    },
    getTemperatureByDate () {
      this.newData = []
      this.newTime = []
      getTemperatureByDate({ gatewayId: this.queryParam.gatewayId }).then(res => {
        console.log(res, 'dfksh')
        for (let i = 0; i < res.data.length; i++) {
          this.newData.push(res.data[i].temperature * 1)
        }
        for (let j = 0; j < res.data.length; j++) {
          this.newTime.push(res.data[j].createTime.slice(5, 16))
        }
        // console.log(this.newData,'bbbbbbbb');
      })
    },
      del (record) {
        del(record).then((res) => {
          if (res.success) {
            this.$message.success('删除成功')
            this.$refs.table.refresh()
          } else {
            this.$message.error('删除失败：' + res.message)
          }
        }).catch((err) => {
          this.$message.error('删除错误：' + err.message)
        })
      },
      getGatewayList (stationId) {
        gatewayList({ stationId: stationId }).then(res => {
          if (res.success) {
            this.gatewayList = res.data
            this.gatewayIds = []
            this.gatewayList.filter(value => {
              this.gatewayIds.push(value.id)
            })
            this.queryParam.gatewayIds = this.gatewayIds.toString()
            this.handleOk()
          }
        })
      },
      toggleAdvanced () {
        this.advanced = !this.advanced
      },
      getStationTree () {
        treeList(Object.assign(this.queryParam)).then(res => {
          this.treeLoading = false
          if (!res.success) {
            return
          }
          this.treeList = res.data
        })
      },
      handleClick (e) {
        if (e.length > 0) {
          this.queryParam = {}
          this.stationId = e.toString()
          this.getGatewayList(e.toString())
        } else {
          this.queryParam.gatewayIds = ''
          this.handleOk()
        }
      },
      handleOk () {
        this.$refs.table.refresh()
      },
      onSelectChange (selectedRowKeys, selectedRows) {
        this.selectedRowKeys = selectedRowKeys
        this.selectedRows = selectedRows
      }
    }
  }
</script>

<style lang="less" scoped>
.table-operator {
  margin-bottom: 18px;
}
button {
  margin-right: 8px;
}
.example {
  text-align: center;
  background: rgba(0, 0, 0, 0.05);
  border-radius: 4px;
  margin-bottom: 20px;
  padding: 10px 20px;
  // margin: 10px 0;
}
.table-page-search-wrapper{
  padding-left: 10px;
  /deep/ .ant-row{
    margin-left: 0px !important;
  }
}
</style>
